//
//  ViewController.m
//  ImitateWeChatSearchBar
//
//  Created by lirenqiang on 2016/11/10.
//  Copyright © 2016年 1111. All rights reserved.
//

#import "ViewController.h"

@interface ViewController () <UISearchBarDelegate>
@property (nonatomic, strong) UISearchBar *searchBar;
@property (nonatomic, strong) UIView *searchView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    [self setupUI];
}

- (void)setupUI
{
    self.view.backgroundColor = [UIColor redColor];
    self.searchBar.frame = CGRectMake(0, 0, kScreenW-20, 44);
    self.searchView.frame = CGRectMake(0, 64, kScreenW, 44);
    [self.view addSubview:self.searchView];
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

#pragma mark - 懒加载
- (UIView *)searchView
{
    if (!_searchView) {
        _searchView = [UIView new];
        _searchView.backgroundColor = [UIColor colorWithRed:201.0/255.0 green:201.0/255.0 blue:206.0/255.0 alpha:1.0];
        [_searchView addSubview:self.searchBar];
    }
    return _searchView;
}

- (UISearchBar *)searchBar
{
    if (!_searchBar) {
        _searchBar = [UISearchBar new];
        _searchBar.placeholder = @"搜索";
        _searchBar.delegate = self;
        _searchBar.searchBarStyle = UISearchBarStyleMinimal;
    }
    return _searchBar;
}

#pragma mark searchBar Delegate method
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar {
    
    [UIView animateWithDuration:0.5 animations:^{
//        self.navigationController.navigationBar.transform = CGAffineTransformMakeTranslation(0, -64);
        self.navigationController.navigationBar.frame = CGRectMake(0, -64, kScreenW, 64);
        self.searchView.frame = CGRectMake(0, 0, kScreenW, 64);
        self.searchBar.frame = CGRectMake(0, 20, kScreenW-20, 44);
    }];
    
    
    self.searchBar.showsCancelButton = YES;
    for(UIView *view in  [[[searchBar subviews] objectAtIndex:0] subviews]) {
        if([view isKindOfClass:[NSClassFromString(@"UINavigationButton") class]]) {
            UIButton * cancel =(UIButton *)view;
            [cancel setTitle:@"取消" forState:UIControlStateNormal];
            [cancel setTitleColor:[UIColor greenColor] forState:UIControlStateNormal];
        }
    }
    return YES;
}

- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar
{
    [UIView animateWithDuration:0.5 animations:^{
                self.navigationController.navigationBar.transform = CGAffineTransformIdentity;
        self.searchView.frame = CGRectMake(0, 64, kScreenW, 44);
        self.searchBar.frame = CGRectMake(0, 0, kScreenW-20, 44);
    }];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    [self.view endEditing:YES];
    self.searchBar.showsCancelButton = NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
